package stephen.com.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

//拦截登录后进入的servlet
@WebFilter("/index.jsp")
public class LoginFilter implements Filter {

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
	}

	@Override
	public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse,
	                     FilterChain filterChain) throws IOException, ServletException {
		HttpServletRequest req = (HttpServletRequest)servletRequest;
		HttpServletResponse resp = (HttpServletResponse)servletResponse;

		//如果点击了记住我
		Cookie[] cookies = req.getCookies();
		if ( null != cookies && cookies.length > 0 ) {
			boolean flag = false;
			for ( Cookie c : cookies ) {
				if ( "userCookie".equals(c.getName()) ) {
					flag = true;
					System.out.println("userCookie存在！");
					break;
				}
				System.out.println("userCookie不存在！");
			}
			if ( flag ) {
				Object obj = req.getSession().getAttribute("userId");
				if ( null != obj ) {
					resp.sendRedirect(req.getContextPath() + "/view/home");
				}
			}
			//用户登录在线后，只有cookie还存在用户登录信息，则直接跳转home，不需要每次都登录
			//如果cookie过期，则只能永远停留在当前页面，必须退出重新登录才能访问其他资源
		}
		filterChain.doFilter(req, resp);
	}

	@Override
	public void destroy() {

	}
}
